package com.utilmodule;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

/**
 * 收集错误日志发送到邮箱
 * 
 * @author liuhongyuan
 * 
 */
public class CrashLogHandlerTools implements UncaughtExceptionHandler {

	private Activity _activity = null;
	private static final boolean sendEmail = false;

	public static CrashLogHandlerTools createHandler(Context activity) {
		CrashLogHandlerTools handler = new CrashLogHandlerTools();
		handler._activity = (Activity) activity;
		return handler;
	}

	@Override
	public void uncaughtException(Thread arg0, Throwable arg1) {
		// Process process = Runtime.getRuntime().exec
		// ( commandLine.toArray( new String[commandLine.size()]));
		// BufferedReader bufferedReader = new BufferedReader
		// ( new InputStreamReader(process.getInputStream()), 1024);
		final Thread thread = arg0;
		final Throwable throwable = arg1;
		SharedPreferences prefs = _activity.getPreferences(0);
		if (sendEmail == prefs.getBoolean("send_crash", true))
			try {
				Writer writer = new StringWriter();
				PrintWriter printWriter = new PrintWriter(writer);
				throwable.printStackTrace(printWriter);

				Intent intent = new Intent(android.content.Intent.ACTION_SEND);
				intent.setType("plain/text");
				String[] strEmailReciver = { "397706720@qq.com" };
				String strEmailBody = writer.toString();
				int versionCode = 0;
				try {
					PackageInfo info;
					info = _activity.getPackageManager().getPackageInfo(
							_activity.getPackageName(), 0);

					String versionName = info.versionName;
					strEmailBody += "versionName: " + versionName + "\n";
					versionCode = info.versionCode;
					strEmailBody += "versionCode: " + versionCode + "\n";
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				intent.putExtra(android.content.Intent.EXTRA_EMAIL,
						strEmailReciver);
				intent.putExtra(Intent.EXTRA_SUBJECT, "crash version"
						+ versionCode + ",系统版本" + android.os.Build.VERSION.RELEASE
						+ "  " + (int) (Math.random() * 100000));
				intent.putExtra(android.content.Intent.EXTRA_TEXT, strEmailBody);
				_activity.startActivity(Intent.createChooser(intent,
						"send crash report"));
				_activity.finish();
				android.os.Process.killProcess(android.os.Process.myPid());
				System.exit(10);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		else {
			Thread.getDefaultUncaughtExceptionHandler().uncaughtException(
					thread, throwable);
		}
	}

}
